package com.example.update.service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class TestWrite {
    public static void main(String[] args) throws IOException {
        Contacts.Builder contactsBuilder = Contacts.newBuilder();
        // 读取已存在的contacts
        try {
            contactsBuilder.mergeFrom(new
                    FileInputStream("src/main/java/com/example/service/contacts.bin"));
        } catch (FileNotFoundException e) {
            System.out.println("contacts.bin not found. Creating a new file.");
        }

        // 新增⼀个联系⼈
        contactsBuilder.addContacts(addPeopleInfo());
        // 将新的contacts写回磁盘
        FileOutputStream output = new FileOutputStream("src/main/java/com/example/update/contacts.bin");
        contactsBuilder.build().writeTo(output);
        output.close();
    }

    private static PeopleInfo addPeopleInfo() {
        Scanner scan = new Scanner(System.in);
        PeopleInfo.Builder peopleBuilder = PeopleInfo.newBuilder();

        System.out.println("-------------新增联系⼈-------------");
        System.out.print("请输⼊联系⼈姓名: ");
        String name = scan.nextLine();
        peopleBuilder.setName(name);

//        System.out.print("请输⼊联系⼈年龄: ");
//        int age = scan.nextInt();
//        peopleBuilder.setAge(age);
//        scan.nextLine();

        System.out.print("请输⼊联系⼈生日: ");
        int bir = scan.nextInt();
        peopleBuilder.setBirthday(bir);
        scan.nextLine();

        for (int i = 0; ; i++) {
            System.out.print("请输⼊联系⼈电话" + (i + 1) + "(只输⼊回⻋完成电话新 增): ");
            String number = scan.nextLine();
            if (number.isEmpty()) {
                break;
            }
            PeopleInfo.Phone.Builder phoneBuilder = PeopleInfo.Phone.newBuilder();
            phoneBuilder.setNumber(number);
            peopleBuilder.addPhone(phoneBuilder);
        }
        System.out.println("-------------添加联系⼈成功-------------");
        return peopleBuilder.build();
    }
}
